package 力扣;

import java.util.ArrayList;

/**
 * @author yyq
 * @create 2022-04-18 14:20
 */
public class leetcode501 {
    public static void main(String[] args) {
        TreeNode root=new TreeNode(1);
        root.right=new TreeNode(2);
        root.right.left=new TreeNode(2);
        findMode(root);
    }
    public static int[] findMode(TreeNode root) {
        int[] count = new int[1];
        int[] maxCount = new int[1];
        maxCount[0] = 1;
        int[] temp = new int[1];
        ArrayList<Integer> list=new ArrayList<>();
        int[] start = new int[1];
        start[0] = -1;
        inOrder(root,count,maxCount,temp,start,list);
        int[] ints=new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ints[i] = list.get(i);
        }
        return ints;
    }

    private static void inOrder(TreeNode root, int[] count, int[] maxCount, int[] temp, int[] start, ArrayList<Integer> list) {
        if(root.left!=null){
            inOrder(root.left,count,maxCount,temp,start,list);
        }
        if(start[0]==-1){
            start[0] = 1;
            temp[0] =root.val;
            count[0] = 1;
            list.add(temp[0]);
        }
        else {
            if(temp[0]==root.val) {
                count[0]++;
                if(count[0]==maxCount[0]){
                    list.add(temp[0]);
                }
                if(count[0]>maxCount[0]) {
                    maxCount[0] = count[0];
                    while (!list.isEmpty()){
                        list.remove(0);
                    }
                    list.add(temp[0]);
                }
            }
            else {
                temp[0] = root.val;
                count[0] = 1;
                if(count[0]==maxCount[0]) list.add(temp[0]);
            }
        }
        if(root.right!=null){
            inOrder(root.right,count,maxCount,temp,start,list);
        }
    }

}
